package com.quyunshuo.module.home.activity.concentration

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.media.MediaPlayer
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.OvershootInterpolator
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.google.android.material.animation.AnimatorSetCompat.playTogether
import com.quyunshuo.edwinpro.common.ui.BaseActivity
import com.quyunshuo.module.home.activity.result.ResultActivity
import com.quyunshuo.module.home.databinding.HomeActivityConcentrationBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit

@AndroidEntryPoint
class ConcentrationActivity :
    BaseActivity<HomeActivityConcentrationBinding, ConcentrationViewModel>() {

    companion object {
        fun newInstance(context: Context, minutes: Long) {

            context.startActivity(Intent(context, ConcentrationActivity::class.java).apply {
                putExtra("minutes", minutes)
            })
        }
    }

    private val mediaPlayer by lazy {
        MediaPlayer().apply {
            // 初始化媒体播放器

            // 设置播放完成监听器，实现循环播放
            setOnCompletionListener {
                if (this@ConcentrationActivity.isPlaying) {
                    seekTo(0) // 回到开头
                    start()   // 重新开始播放
                }
            }
            // 设置准备完成监听器
            setOnPreparedListener {
                this@ConcentrationActivity.isPlaying = true
                start()
            }
        }
    }
    private var isPlaying = false
    private val mp3FileName = "xm3622.mp3" // 替换为你的MP3文件名

    // 时间格式化工具
    private val hourFormat = SimpleDateFormat("HH", Locale.getDefault())
    private val minuteFormat = SimpleDateFormat("mm", Locale.getDefault())

    // 时间更新处理器
    private val handler = Handler(Looper.getMainLooper())
    private val updateRunnable = object : Runnable {
        override fun run() {
            updateTime()
            handler.postDelayed(this, TimeUnit.SECONDS.toMillis(30)) // 每30秒更新一次
        }
    }
    private val totalMinutes by lazy {
        intent.getLongExtra("minutes", 1)
    }
    private var timeLeft = 0L // 剩余毫秒数
    private var isRunning = false
    private var timerJob: Job? = null


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // 立即更新一次时间
        updateTime()
        // 开始定期更新
        handler.postDelayed(updateRunnable, TimeUnit.SECONDS.toMillis(30))
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // 移除更新回调，防止内存泄漏
        handler.removeCallbacks(updateRunnable)
    }

    private fun updateTime() {
        val calendar = Calendar.getInstance()
        val currentHour = hourFormat.format(calendar.time)
        val currentMinute = minuteFormat.format(calendar.time)

        // 将小时和分钟分别设置到两个TextView
        mBinding.hour.text = currentHour
        mBinding.minute.text = currentMinute

    }

    private val TOTAL_TIME: Float = 3000.0f // 3秒总时长
    private val INTERVAL: Int = 100 // 100ms更新间隔

    /**
     * 通过 viewModels() + Hilt 获取 ViewModel 实例
     */
    override val mViewModel by viewModels<ConcentrationViewModel>()


    override fun createVB() = HomeActivityConcentrationBinding.inflate(layoutInflater)

    private var timeJob: Job? = null
    private var timeNub: Int = 0

    @SuppressLint("ClickableViewAccessibility")
    override fun HomeActivityConcentrationBinding.initView() {
        Log.d("wenlong", "initView: $totalMinutes ")
        back.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_UP -> {
                    progress.isVisible = false
                    stopTime()
                    return@setOnTouchListener true
                }

                MotionEvent.ACTION_DOWN -> {
                    progress.isVisible = true
                    startTime()
                    return@setOnTouchListener true
                }

                else -> {
                    return@setOnTouchListener true
                }
            }
        }


        // 返回格式化后的字符串
        timeUp.text = addFiveMinutesToCurrentTime()

        hour.post {startAnimation(hour)}
        minute.post {startAnimation(minute)}

        startPlayback()
    }

    fun addFiveMinutesToCurrentTime(): String {
        // 获取当前时间的 Calendar 实例
        val calendar = Calendar.getInstance()
        // 添加 5 分钟
        calendar.add(Calendar.MINUTE, totalMinutes.toInt())
        // 格式化为 HH:mm 格式
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        // 返回格式化后的字符串
        return String.format("%02d:%02d", hour, minute)
    }

    override fun onResume() {
        super.onResume()
        startTimer()
    }

    override fun onPause() {
        super.onPause()
        pauseTimer()
    }

    override fun onDestroy() {
        super.onDestroy()
        timerJob?.cancel()
        // 释放媒体播放器资源
        mediaPlayer.release()
    }

    //暂停
    private fun toggleTimer() {
        if (isRunning) pauseTimer() else startTimer()
    }

    private fun startTimer() {
        if (isRunning) return
        isRunning = true
        timeLeft = totalMinutes * 60000L
        timerJob?.cancel()
        timerJob = lifecycleScope.launch {
            while (isActive) {
                timeLeft -= 1000
                Log.d("wenlong", "startTimer: $timeLeft")
                withContext(Dispatchers.Main) {
                    // 检查是否结束
                    if (timeLeft <= 0) toResult()
                }

                // 每秒更新一次
                delay(1000)
            }
        }
    }

    private fun toResult() {
        ResultActivity.newInstance(this@ConcentrationActivity, totalMinutes)
        finish()
    }

    private fun pauseTimer() {
        isRunning = false
        timerJob?.cancel()
    }


    private fun startTime() {
        stopTime()
        timeJob = lifecycleScope.launch() {
            runCatching {
                withContext(Dispatchers.Default) {
                    while (isActive) {
                        delay(100)
                        timeNub += INTERVAL
                        val progress = (timeNub / TOTAL_TIME * 100).toInt()
                        launch(Dispatchers.Main) {
                            mBinding.progress.progress = progress
                        }
                        if (progress >= 100) {
                            withContext(Dispatchers.Main) {
                                toResult()
                            }
                            break
                        }

                    }
                }

            }

        }
    }

    private fun stopTime() {
        timeJob?.cancel()
        timeNub = 0 // 重置计时
        mBinding.progress.progress = 0
    }


    private fun startPlayback() {
        if (isPlaying) return

        try {
            // 从assets目录打开MP3文件
            val assetFileDescriptor: AssetFileDescriptor = assets.openFd(mp3FileName)

            // 重置媒体播放器状态
            mediaPlayer.reset()

            // 设置数据源
            mediaPlayer.setDataSource(
                assetFileDescriptor.fileDescriptor,
                assetFileDescriptor.startOffset,
                assetFileDescriptor.length
            )

            // 准备播放（异步）
            mediaPlayer.prepareAsync()
            // 关闭文件描述符
            assetFileDescriptor.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun stopPlayback() {
        if (isPlaying) {
            mediaPlayer.pause()
            isPlaying = false
        }
    }


    private fun startAnimation(view: View) {
        Log.d("wenlong", "startAnimation: ${view.height}")
        Log.d("wenlong", "startAnimation: ${view.measuredHeight}")
        // 重置为初始状态
        view.alpha = 0f
        view.translationY = view.height.toFloat()

        // 1. 透明度动画 - 从透明到显示
        val alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f).apply {
            duration = 1200
        }
        // 2. 移动动画 - 从底部移动到原始位置
        val translationAnimator = ObjectAnimator.ofFloat(view, "translationY", view.height.toFloat(), 0f).apply {
            interpolator = OvershootInterpolator(0.8f) // 添加弹性效果
            duration = 1500
        }


        // 创建动画集
        AnimatorSet().apply {
            playTogether(
                alphaAnimator,
                translationAnimator,
            )
            interpolator = AccelerateDecelerateInterpolator()
            startDelay = 500
            start()
        }
    }

    override fun HomeActivityConcentrationBinding.initListener() {

    }


    override fun initObserve() {


    }


    override fun initRequestData() {

    }

    override fun onBackPressed() {
    }
}